<?php

namespace Common\Model;
class ModelFieldModel extends BaseModel
{
    protected $_auto = array(
        array('create_time', NOW_TIME,),
        array('update_time', NOW_TIME, 3),
    );
    protected $_validate = array(
        array('name', 'require', '请填写字段标识',),
        array('title', 'require', '请填写字段标题',),
        array('model_id', 'require', '请填写模型'),
        array('attribute', 'require', '请填写字段属性'),
    );
    protected $update_list = array();
    protected $delete_list = array();

    /**
     * 解析字段类型
     * @return mixed
     */
    public function parseFieldType()
    {
        $type = C('MODEL_FIELD_TYPE');
        foreach ($type as $key => &$row) {
            $row = explode('|', $row);
        }
        return $type;
    }

    /**
     * 解析字段表单参数
     * @param $data
     * @return array
     */
    public function parseFieldParam($data)
    {
        $array = preg_split('/[\r\n]+/', trim($data, "\r\n"));
        $n = array();
        foreach ($array as $row) {
            $key = substr($row, 0, strpos($row, ':'));
            $val = htmlspecialchars_decode(substr($row, strpos($row, ':') + 1));
            $json = json_decode($val, true);
            if ($json) {
                $val = $json;
            }
            $n[$key] = $val;
        }
        return $n;
    }

    /**
     * 获取字段验证规则
     * @param $fields
     * @return array
     */
    public function getFieldsValidateRules($fields)
    {
        $rules = array();
        foreach ($fields as $row) {
            if ($row['validate_rule'] || $row['validate_type'] == 'unique') {
                switch ($row['validate_type']) {
                    case 'regex':
                    case 'function':
                    case 'unique':
                    case 'length':
                    case 'in':
                    case 'notin':
                    case 'between':
                    case 'notbetween':
                        $rules[] = array($row['name'], $row['validate_rule'], $row['error_info'], 0, $row['validate_type'], intval($row['validate_time']));// 构建规则
                        break;
                }
            }
            unset($row);
        }
        return $rules;
    }
    public function getFieldsAutoRules($fields) {
        $rules = array();
        foreach ($fields as $row) {
            if ($row['auto_rule']) {
                $rules[] = array($row['name'], $row['auto_rule'], $row['auto_time'], $row['auto_type']);
            }
        }
        return $rules;
    }

    public function getFormFields($model_id)
    {
        $map = array(
//            'is_show'=>1,
            'model_id' => $model_id
        );
        $result = $this->where($map)->select();
        foreach ($result as &$item) {
            $item['form_param'] = $this->parseFieldParam($item['form_param']);
        }
        return $result;
    }

    // 插入前检测
    protected function _before_insert(&$data, $options)
    {
        parent::_before_insert($data, $options);
        if ($data['name'] && $data['model_id']) {
            $map = array('model_id' => $data['model_id'], 'name' => $data['name']);
            if ($this->where($map)->count()) {
                $this->error = '该字段已存在';
                return false; // 字段重复
            }
        }
    }

    // 新增前置
    protected function _after_insert($data, $options)
    {
        parent::_after_insert($data, $options);
        $mDao = D('Model'); // 模型
        if ($data['model_id']) {
            $modelName = $mDao->getFieldById($data['model_id'], 'name'); // 获取表模型标识
            $tbn = C('DB_PREFIX') . $modelName; // 组装表名
            $mDao->addColumn($tbn, $data['name'], $data['attribute'], false, $data['value'], $data['title']); // 新增字段
        }
    }

    // 修改字段
    protected function _before_update(&$data, $options)
    {
        parent::_before_update($data, $options);
        if ($data['name'] && $data['model_id']) {
            $id = $this->where($options['where'])->getField('id');
            $map = array('model_id' => $data['model_id'], 'name' => $data['name'], 'id' => array('neq', $id));
            if ($this->where($map)->count()) {
                $this->error = '该字段已存在';
                return false; // 字段重复
            }
        }
        if ($options['where']) {
            $this->update_list = $this->where($options['where'])->select();
        }
    }

    protected function _after_update($data, $options)
    {
        parent::_after_update($data, $options);
        $mDao = D('Model'); // 模型
        if ($this->update_list) {
            foreach ($this->update_list as &$item) {
                $modelName = $mDao->getFieldById($item['model_id'], 'name'); //
                $tbn = C('DB_PREFIX') . $modelName; // 组装表名
                $mDao->alterColumnAttr($tbn, $item['name'], $data['name'], $data['attribute'], 0, $data['title']);
                $data['value'] && $mDao->setColumnDefault($tbn, $data['name'], $data['value']);
            }
        }
    }

    // 删除字段
    protected function _before_delete($options)
    {
        parent::_before_delete($options);
        if ($options['where']) {
            $this->delete_list = $this->where($options['where'])->select();
        }
    }

    protected function _after_delete($data, $options)
    {
        parent::_after_delete($data, $options);
        if ($this->delete_list) {
            $mDao = D('Model'); // 模型
            foreach ($this->delete_list as $item) {
                $modelName = $mDao->getFieldById($item['model_id'], 'name'); //
                $tbn = C('DB_PREFIX') . $modelName; // 组装表名
                $mDao->dropColumn($tbn, $item['name']);
            }
        }
    }
}